﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestRT;
using Remindme.Repository.Interfaces;
using Remindme.Model;

namespace Remindme.Repository
{
    public class ItemRepository : IItemRepository
    {
        private RestClient restClient;

        public ItemRepository()
        {
            restClient = new RestClient("http://getpocket.com/v3/");
            restClient.AddDefaultHeader("X-Accept", "application/json");
        }

        public Task<ItemModel> CreateAsync(ItemModel obj)
        {
            throw new NotImplementedException();
        }

        public Task UpdateAsync(ItemModel obj)
        {
            throw new NotImplementedException();
        }

        public Task DeleteAsync(int objKey)
        {
            throw new NotImplementedException();
        }

        public Task<ItemModel> FindAsync(int objKey)
        {
            throw new NotImplementedException();
        }

        async public Task<List<ItemModel>> FindAllAsync()
        {
            AppUtils.SettingsManager settings = App.Current.Resources["Settings"] as AppUtils.SettingsManager;
            List<ItemModel> allItems = new List<ItemModel>();

            IRestRequest request = new RestRequest("get.php");
            request.AddParameter("consumer_key", Other.Secrets.WIN8_CONSUMER_KEY);
            request.AddParameter("access_token", settings.AccessTokenSetting);
            request.AddParameter("detailType", "complete");
            request.AddParameter("count", 10);

            IRestResponse response = await restClient.PostAsync(request);
            if (response.ErrorException != null) // Ocurrió un error en la petición
            {
                var ex = new Exceptions.CustomException(response.ErrorMessage);
                throw ex;
            }

            var deserializer = new RestRT.Deserializers.JsonDeserializer();
            var apiResponse = deserializer.Deserialize(response, typeof(ComplexApiResponse));

            foreach (var keyValuePair in ((ComplexApiResponse)apiResponse).list)
            {
                allItems.Add(keyValuePair.Value);
            }

            return allItems;
        }

        private class ComplexApiResponse
        {
            public int status { get; set; }
            public int complete { get; set; }
            public System.Collections.Generic.Dictionary<string, Model.ItemModel> list { get; set; }
        }
    }
}
